import asyncio
import time
import ygg_aiomysql as aiomysql

async def main():
    """
    演示自动创建不存在的数据库
    """
    # 使用时间戳生成唯一数据库名
    test_db_name = f"test_db_{int(time.time())}"
    print(f"将尝试创建数据库: {test_db_name}")
    
    # 创建连接池，指定不存在的数据库名
    pool = await aiomysql.new_pool(
        host='localhost',
        port=3306,
        user='root',
        password='zhangdapeng520',
        db=test_db_name
    )
    
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            # 验证数据库已创建
            await cur.execute("SHOW DATABASES")
            databases = [db[0] for db in await cur.fetchall()]
            print("当前所有数据库:")
            for db in databases:
                print(f"- {db}")
            
            assert test_db_name in databases
            print(f"\n数据库 {test_db_name} 创建成功!")
            
            # 使用新创建的数据库
            await cur.execute(f"USE {test_db_name}")
            await cur.execute("CREATE TABLE IF NOT EXISTS test (id INT)")
            await cur.execute("INSERT INTO test VALUES (1)")
            await cur.execute("SELECT * FROM test")
            result = await cur.fetchone()
            print(f"\n测试查询结果: {result[0]}")
    
    # 关闭连接池
    pool.close()
    await pool.wait_closed()
    
    # 清理测试数据库
    async with (await aiomysql.new_pool(
        host='localhost',
        port=3306,
        user='root',
        password='zhangdapeng520'
    )).acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(f"DROP DATABASE {test_db_name}")
    print(f"\n已清理测试数据库: {test_db_name}")

if __name__ == '__main__':
    asyncio.run(main())